<?php

/**
 * 市场的模型
 * 2022-03/03 --by low
 */
class Market_model extends CI_Model
{

    // 上架市场
    public function addGoods($data)
    {
        $this->db->insert('1_market', [
            'sell_uid' => $data['uid'],
            'cid' => $data['cid'],
            'price' => $data['price'],
            'time' => time(),
            'ip' => $_SERVER['REMOTE_ADDR'],
            'status' => $data['status']
        ]);
        return $this->db->insert_id();
    }

    // 市场列表
    public function marketList($param = [], $page, $pageSize, $order = [])
    {
        if (empty($param['cid'])) {
            return null;
        }
        $query = $this->db
            ->select('a.id,a.cid,a.lock,a.status,a.price as new_price,b.catid,b.title,b.number,b.total,b.thumb,b.price')
            ->from('1_market as a')
            ->join('1_favorite_my as b', 'a.cid=b.id')->where(['a.cid' => $param['cid']]);
        if ($param['keyword']) {
            $query->like("a.title", $param['keyword']);
        }
        if ($order) {
            $query->order_by("a.{$order['order']} {$order['sort']}");
        }
        return $query->limit($pageSize, ($page - 1) * $pageSize)
            ->get()->result_array();
    }

    // 市场中商品的详情 连表
    public function goodsInfo($id)
    {
        return $this->db
            ->select('a.id,a.cid,a.sell_uid,a.lock,a.status,b.catid,b.title,b.number,b.total,b.thumb,b.price,b.cid as good_id,b.catid')
            ->from('1_market as a')
            ->join('1_favorite_my as b', 'a.cid=b.id')
            ->where('a.id', $id)->limit(1)->get()->row_array();
    }

    //仅仅获取市场中商品的详情
    public function goodInfo($condition, $select = '*')
    {
        if (empty($condition) || !is_array($condition)) {
            return false;
        }
        return $this->db->select($select)
            ->where($condition)->limit(1)->get('1_market')->row_array();
    }

    // 操作自己的物品信息
    public function operateGood($id, $data)
    {
        if (empty($id) || empty($data)) {
            return false;
        }
        $keys = array_keys($data);
        foreach ($keys as $key) {
            if (!in_array($key, ['status', 'lock', 'buy_uid', 'buy_time', 'price'])) {
                return false;
            }
        }
        return $this->db->set($data)->where('id', $id)->update('1_market');
    }

    // 转义
    public function goodsTransfer($item = [])
    {
        if ($item['time']) {
            $item['time'] = date('Y-m-d H:i', $item['time']);
        }
        if ($item['thumb']) {
            $item['thumb'] = dr_thumb($item['thumb'], 500, 500);
        }
        return $item;
    }

    // 取出市场内的分类. -->视图
    public function marketCategory($cid = '', $page, $pageSize)
    {
        $query = $this->db->select('id,title,thumb,price');
        if ($cid) {
            $query->where('catid', $cid);
        }
        return $query->limit($pageSize, ($page - 1) * $pageSize)
            ->get('1_market_category')->result_array();
    }

    // 对应首页推荐的市场内容
    public function getRecommend($page, $pageSize)
    {
        return $this->db->select('id,title,thumb,price')
            ->limit($pageSize, ($page - 1) * $pageSize)
            ->get('1_recommend_category')->result_array();
    }

    // 添加市场种的价格记录
    public function addPriceLog($data)
    {
        return $this->db->insert('1_market_price_log', $data);
    }

    // 市场订单
    public function addMarketOrder($data)
    {
        $this->db->insert('1_market_order', [
            'sn' => $this->createSn(),
            'buy_uid' => $data['member']['uid'],
            'buy_name' => $data['member']['name'],
            'sell_uid' => $data['info']['sell_uid'],
            'sell_name' => $data['info']['author'],
            'market_id' => $data['info']['id'],
            'my_id' => $data['info']['cid'],
            'cid' => $data['info']['good_id'],
            'catid' => $data['info']['catid'],
            'thumb' => $data['info']['thumb'],
            'price' => $data['info']['price'],
            'num' => $data['info']['number'],
            'total' => $data['info']['total'],
            'order_time' => time(),
            'order_status' => 1,
            'pay_id' => 0,
            'pay_time' => 0,
            'pay_status' => 0,
            'team_code' => $data['member']['team_code'] ?: ''
        ]);
        return $this->db->insert_id();
    }

    // 生成流水订单号
    protected static function createSn(): string
    {
        return date('Ymd') .
            substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    // 更新锁状态
    public function operateLock($id, $value)
    {
        if (empty($id)) {
            return false;
        }
        return $this->db->set('lock', $value)->where('id', $id)->update('1_market');
    }

    // 市场订单详情
    public function marketOrderInfo($id, $select = "*")
    {
        return $this->db
            ->select($select)
            ->where('id', $id)->limit(1)->get('1_market_order')->row_array();
    }

    // 市场订单列表
    public function marketOrderList($param = [], $page, $pageSize): array
    {
        if (!is_array($param)) {
            return [];
        }
        $query = $this->db
            ->select('id,sn,buy_uid,buy_name,sell_uid,sell_name,price,num,total,order_time,order_status,pay_status');
        if ($param['uid']) {
            $query->where('buy_uid', $param['buy_uid']);
        }
        if ($param['start']) {
            $query->where(['order_time >' => $param['start'], 'order_time <' => $param['end']]);
        }
        if ($param['field'] && $param['keyword']) {
            $query->like($param['field'], $param['keyword']);
        }
        $nums = $query->count_all_results('1_market_order', false);
        $list = $query->limit($pageSize, ($page - 1) * $pageSize)->order_by('id desc')->get()->result_array();
        return ['list' => $list, 'num' => $nums];
    }

    //操作订单
    public function operateOrder(int $id, $operate = [])
    {
        if (empty($id) || empty($operate)) {
            return false;
        }
        return $this->db->set($operate)->where("id", $id)->update("1_market_order");
    }

    // 删除订单
    public function delMarketOrder($id)
    {
        return $this->db->{is_array($id) ? 'where_in' : 'where'}('id', $id)->delete('1_market_order');
    }
}